<template>
  <div class="app-container">
    <!-- 查询和其他操作 -->
    <el-form v-show="showSearch" :inline="true" ref="form" :model="params" label-width="68px">
      <el-form-item label="用户名称">
        <el-input style="width: 200px" size="small" v-model="params.username" placeholder="请输入用户名称"/>
      </el-form-item>
      <el-form-item label="状态">
        <el-select style="width: 150px" size="small" v-model="params.state" filterable clearable
                   reserve-keyword
                   @change='handleFind' placeholder="请选择状态"
        >
          <el-option label="正常" value="1"/>
          <el-option label="禁用" value="0"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="small" @click="handleFind">查找</el-button>
        <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            v-if="canAdd"
            type="primary"
            icon="el-icon-plus"
            size="small"
            @click="handleCreate"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            v-if="canDel"
            :disabled="!multipleSelection.length"
            type="danger"
            icon="el-icon-delete"
            size="small"
            @click="handleDelete"
        >批量删除
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="fetchUser"></right-toolbar>
    </el-row>

    <div style="margin-top: 5px">
      <el-table border :data="userData" fit style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" align="center"/>
        <el-table-column prop="avatar" align="center" width="70" label="头像">
          <template slot-scope="scope">
            <img :src="scope.row.avatar" width="40" height="40"/>
          </template>
        </el-table-column>
        <el-table-column prop="username" width="150px" align="center" label="账号"/>
        <el-table-column prop="nickname" width="150px" align="center" label="昵称"/>
        <el-table-column prop="sex" width="60px" align="center" label="性别">
          <template slot-scope="scope">
            {{ sexOptions[scope.row.sex] }}
          </template>
        </el-table-column>
        <el-table-column prop="email" width="150px" align="center" label="邮箱"/>
        <el-table-column prop="phoneNumber" width="150px" align="center" label="手机号"/>
        <el-table-column prop="state" align="center" label="状态">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.state" type="success">
              正常
            </el-tag>
            <el-tag v-if="!scope.row.state" type="danger">
              禁用
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" align="center" width="180" label="创建时间"/>
        <el-table-column prop="loginType" align="center" label="登录方式">
          <template slot-scope="scope">
            <el-tag v-for="item in dictLoginTypeList" v-if="scope.row.loginType === parseInt(item.value)"
                    :type="item.style">
              {{ item.label }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="ipAddress" width="130px" align="center" label="登录IP"/>
        <el-table-column align="center" width="180" label="最后登录时间">
          <template slot-scope="scope">
            <span>{{ scope.row.lastLoginTime }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="150" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button v-if="canUpdate" type="primary" size="mini" @click="handleUpdate(scope)">编辑
            </el-button>
            <el-button v-if="canDel" size="mini" type="danger"
                       @click="handleDelete(scope.row, true)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!--分页区域-->
    <div class="pagination-container" style="float: right;margin-bottom: 1.25rem;margin-top: 1.25rem;">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                     :current-page="params.pageNum" :page-size="params.pageSize" :page-sizes="[10, 20, 30]"
                     layout="total, sizes,prev, pager, next,jumper" :total="total">
      </el-pagination>
    </div>

    <el-dialog center :title="title" :visible.sync="dialogFormVisible">
      <el-form :rules="rules" ref="dataForm" :model="form">
        <el-form-item prop="username" label="账号" :label-width="formLabelWidth">
          <el-input :disabled="this.isEditForm === 1" v-model="form.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="nickname" label="昵称" :label-width="formLabelWidth">
          <el-input v-model="form.nickname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="email" label="邮箱" :label-width="formLabelWidth">
          <el-input v-model="form.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="phoneNumber" label="手机号" :label-width="formLabelWidth">
          <el-input v-model="form.phoneNumber" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="sex" label="性别" :label-width="formLabelWidth">
          <el-radio v-for="(item,index) in sexOptions" v-model="form.sex" :label="index">
            {{ item }}
          </el-radio>
        </el-form-item>
        <el-form-item prop="state" label="状态" :label-width="formLabelWidth">
          <div>
            <el-radio v-model="form.state" :label="true">正常</el-radio>
            <el-radio v-model="form.state" :label="false">禁用</el-radio>
          </div>
        </el-form-item>
        <el-form-item prop="roleIdList" label="角色" :label-width="formLabelWidth">
          <el-select v-model="form.roleIdList" multiple placeholder="请选择角色">
            <el-option
                v-for="item in userRoleList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {fetchUser, remove, create, update, info} from '@/api/user'
import {fetchAllRole} from '@/api/system'
import {mapGetters} from "vuex";
import {hasAuth} from "@/utils/auth";
import {getDataByDictType} from "@/api/dictData";

export default {
  data() {
    return {
      formLabelWidth: '120px',
      icon: false, //控制删除图标的显示
      img: process.env.VUE_APP_IMG_API,
      isEditForm: 0,
      sexOptions: ['男', '女', '未知'],
      dialogFormVisible: false,
      showSearch: true,
      multipleSelection: [],
      // 加载层信息
      loading: [],
      title: '',
      dictLoginTypeList: [],
      loginTypeDefaultValue: null,
      total: 0,
      params: {
        pageNum: 1,
        pageSize: 10,
        username: null,
        state: null
      },
      // 全部角色
      roleList: [],
      // 选中的角色
      userRoleList: [],
      form: {
        id: null,
        username: '',
        nickname: '',
        email: '',
        phoneNumber: '',
        sex: 2,
        state: true,
        roleIdList: [],
        roleList: []
      },
      userData: [],
      rules: {
        username: [
          {required: true, message: '请输入账号', trigger: 'blur'},
          {min: 1, max: 20, message: '长度在1到20个字符'},
        ],
        nickname: [
          {required: true, message: '请输入昵称', trigger: 'blur'},
          {min: 1, max: 20, message: '长度在1到20个字符'},
        ],
        email: [
          {required: true, message: '请输入邮箱', trigger: 'blur'},
          {type: 'email', message: '请输入正确的邮箱', trigger: 'blur'}
        ],
        phoneNumber: [
          {required: false, message: '请输入手机号', trigger: 'blur'},
          {
            type: 'number',
            message: '手机号格式不正确',
            trigger: 'blur',
            transform(value) {
              if (value) {
                var phonereg = 11 && /^((13|14|15|16|17|18|19)[0-9]{1}\d{8})$/
                if (!phonereg.test(value)) {
                  return false
                } else {
                  return Number(value)
                }
              }
              return false;
            }
          }
        ],
        sex: [
          {required: true, message: '请选择性别', trigger: 'blur'}
        ],
        state: [
          {required: true, message: '请选择状态', trigger: 'change'},
        ],
        roleIdList: [
          {required: true, message: '请选择角色', trigger: 'blur'},
        ]
      }
    }
  },
  computed: {
    ...mapGetters([
      'pres'
    ]),
    canAdd: function () {
      return true
    },
    canDel: function () {
      return true
    },
    canUpdate: function () {
      return true
    },
  },
  created() {
    this.openLoading();
    this.getDictList()
    this.fetchAllRole()
    this.fetchUser()
  },
  methods: {
    getDictList: function () {
      let dictTypes = ['sys_login_method'];
      getDataByDictType(dictTypes).then(response => {
        let dictMap = response.data;
        this.dictLoginTypeList = dictMap.sys_login_method.list
        this.loginTypeDefaultValue = dictMap.sys_login_method.defaultValue
      }).catch(err => {
        console.error(err)
      })
    },
    fetchUser: function () {
      fetchUser(this.params).then(res => {
        this.userData = res.data.results;
        this.total = res.data.total
        this.loading.close();
      }).catch(err => {
        console.error(err)
      })
    },
    fetchAllRole: function () {
      fetchAllRole({}).then(res => {
        this.roleList = res.data;
      })
    },
    resetQuery: function () {
      this.params.username = null;
      this.params.state = null;
      this.fetchUser()
    },
    handleFind: function () {
      this.params.pageNum = 1
      this.fetchUser()
    },
    handleCreate: function () {
      this.form = this.getFormObject();
      this.handleRole();
      this.beforeShow("添加用户", 0)
    },
    handleUpdate: function (scope) {
      info(scope.row.id).then(res => {
        this.form = res.data;
        // 角色复选
        const hasRoles = res.data.roleList
        var userRoleIds = [];
        for (let a = 0; a < hasRoles.length; a++) {
          userRoleIds.push(hasRoles[a].id);
        }
        this.$set(this.form, "roleIdList", userRoleIds);

        this.handleRole();
      })
      this.beforeShow("修改用户", 1)
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 处理角色
    handleRole: function () {
      const hasRoles = this.form.roleList;
      const allRoles = this.roleList;
      const roles = [];
      for (let i = 0; i < allRoles.length; i++) {
        let check = false;
        for (let j = 0; j < hasRoles.length; j++) {
          if (allRoles[i].id === hasRoles[j].id) {
            check = true;
          }
        }
        let role = {
          id: allRoles[i].id,
          name: allRoles[i].name,
          code: allRoles[i].code,
          check: check
        };
        roles.push(role);
      }
      this.userRoleList = roles;
    },
    getFormObject: function () {
      return {
        id: null,
        username: '',
        nickname: '',
        email: '',
        phoneNumber: '',
        sex: 2,
        state: true,
        roleIdList: [],
        roleList: []
      }
    },
    beforeShow: function (title, isEditForm) {
      this.title = title
      this.isEditForm = isEditForm
      this.dialogFormVisible = true
    },
    submit: function () {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if (this.isEditForm) {
            update(this.form.id, this.form).then(res => {
              this.$message.success("修改成功")
              this.fetchUser()
              this.close()
            }).catch(err => {
              console.error(err)
            })
          } else {
            create(this.form).then(res => {
              this.$message.success("添加成功")
              this.userData.unshift(res.data)
              this.handleFind();
              this.close()
            }).catch(err => {
              console.error(err)
            })
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      })
    },
    handleDelete: function (row, single) {
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let ids = []
        if (single && single) {
          ids.push(row.id)
        } else {
          this.multipleSelection.forEach(item => {
            ids.push(item.id)
          })
        }
        remove(ids).then(res => {
          this.$message.success("删除用户成功")
          this.fetchUser()
        }).catch(err => {
          console.log(err)
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消删除'
        })
      })
    },
    handleSizeChange: function (val) {
      this.params.pageSize = val
      this.fetchUser()
    },
    handleCurrentChange: function (val) {
      this.params.pageNum = val
      this.fetchUser()
    },
    close() {
      this.dialogFormVisible = false;
      this.form = {}
    },
    handleSelectionChange: function (val) {
      this.multipleSelection = val;
    },
    // 打开加载层
    openLoading: function () {
      this.loading = this.$loading({
        lock: true,
        text: "正在加载中~",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
    },
  }
}
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
